<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;

class Article
{
    use Jump;
    public function index()
    {
        $page_type = 1;
        $where = [];
        $where['status'] = 1;
        $cid = input('get.cid', 0, 'intval');
        if ($cid > 0) {
            $where['category_id'] = $cid;
            $page_type = 2;
        }
        $keyword = input('get.keyword', '', 'clear_html');
        if (!empty($keyword)) {
            $where[] = ['title', 'like', "%{$keyword}%"];
            $page_type = 3;
        }
        $tag = input('get.tag', '', 'clear_html');
        if (!empty($tag)) {
            $tags = widget('common.tags')->get('', ['field' => 'id,title', 'key' => 'sign']); // 所有标签
            $tag_id = $tags[$tag]['id'] ?? 0;
            if ($tag_id > 0) {
                $where[] = ['tag_ids', 'find_in_set', $tag_id];
            }
            $tag = $tags[$tag]['title'] ?? $tag;
            $page_type = 4;
        }
        $fields = 'id,thumb,title,summary,category_id,tag_ids,user_id,author,is_top,read_count,update_time';
        $list=db('article')->field($fields)->where($where)->order('is_top DESC,update_time DESC,id DESC')->paginate(16);
        return view()->with(['list' => $list, 'page_type' => $page_type, 'keyword' => $keyword, 'cid' => $cid, 'tag' => $tag]);
    }

    public function detail(int $id)
    {
        $vo = db('article')->where('id', $id)->find();
        if (!$vo) {
            $this->error('记录不存在');
        }
        // 真实浏览量
        if ($id != cookie('read-id')) {
            db('article')->where('id', $id)->setInc('read_count');
            cookie('read-id', $id);
            $vo['read_count'] ++;
        }
        // 是否显示
        $vo['is_display'] = $vo['is_password'] ? cookie('pass-id'.$id) : 1;
        return view()->with(['vo' => $vo]);
    }

    public function check_password()
    {
        if ($this->isPost()) {
            $id = input('post.id', 0, 'intval');
            $password = input('post.password', '', 'clear_html');
            if (empty($password)) {
                $this->error('请输入访问密码');
            }
            $vo = db('article')->field('id')->where('id', $id)->where('password', $password)->where('status=1')->find();
            if (!$vo) {
                $this->error('密码错误');
            } else {
                cookie('pass-id'.$id, 1);
                $this->success('验证成功，正在显示...', 'article/detail?id='.$id);
            }
        }
        $this->error('非法操作');
    }
}